package com.chii.color.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author chii
 */
public class OkHttpHelp {
    private static OkHttpClient okHttpClient;
    public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("image/jpg");

    public OkHttpHelp() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient.Builder()
                    //设置连接超时时间
                    .connectTimeout(20, TimeUnit.SECONDS)
                    //设置读取超时时间
                    .readTimeout(30, TimeUnit.SECONDS)
                    .build();
        }
    }

    public int check(String url) {
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = okHttpClient.newCall(request).execute();
            return response.code();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 404;

    }

    public String get(String url, Map<String, String> params) throws IOException {
        HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();

        if (params != null) {
            for (Map.Entry<String, String> param : params.entrySet()) {
                httpBuilder.addQueryParameter(param.getKey(), param.getValue());
            }
        }
        Request request = new Request.Builder()
                .url(httpBuilder.build())
                .build();
        String content = null;

        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                content = response.body().string();
            }
        }
        return content;
    }

    public JSONObject postImage(String url, Map<String, String> params, File file) throws IOException {
        HttpUrl.Builder httpBuilder = HttpUrl.parse(url).newBuilder();
        RequestBody fileBody = RequestBody.create(file, MEDIA_TYPE_MARKDOWN);
        MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder();
        requestBodyBuilder.setType(MultipartBody.FORM).addFormDataPart("files", file.getName(), fileBody);
        //添加其他参数
        for (Map.Entry<String, String> param : params.entrySet()) {
            requestBodyBuilder.addFormDataPart(param.getKey(), param.getValue());
        }
        MultipartBody requestBody = requestBodyBuilder.build();

        Request request = new Request.Builder()
                .url(httpBuilder.build())
                .post(requestBody)
                .build();

        String content = null;
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (response.isSuccessful()) {
                content = response.body().string();
            }
        }
        return (JSONObject) JSON.parse(content);
    }

}
